package com.itdev.matcherapp.android.gtalkclient;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Im;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gtalkservice.IGTalkService;
import com.google.android.gtalkservice.IGTalkSession;
import com.itdev.matcherapp.android.R;


public class ContactList extends ListActivity{

	private ContentResolver contentResolver;
	private Cursor cursorContact;
	private Cursor cursorInvited;
	private IGTalkSession mGTalkSession;
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		final String from[] = new String[]{Im.Contacts.USERNAME, Im.Contacts.PRESENCE_STATUS};
		final int to[] = new int[]{R.id.username, R.id.userpresence};
		setContentView(R.layout.contact_list);
		bindService();
		contentResolver = getContentResolver();
		cursorContact = contentResolver.query(Im.Contacts.CONTENT_URI, null, null, null, null);
		cursorInvited = contentResolver.query(Im.Subscriptions.CONTENT_URI, null, null, null, null);
		initCursorInvited();
		setListAdapter(new SimpleCursorAdapter(this, R.layout.contact_item, cursorContact, from, to){

			@Override
			public void setViewText(TextView v, String text) {
				// TODO Auto-generated method stub
				if(v.getId() == R.id.userpresence)
					super.setViewText(v, convertPresenseStatusToText(text));
				else
					super.setViewText(v, text);
			}
		});
	}
	
	private void initCursorInvited() {
//		cursorInvited.registerContentObserver(new ContentObserver(null){
//
//			@Override
//			public void onChange(boolean arg0) {
//				Toast.makeText(getParent(), "Invited", Toast.LENGTH_LONG);
//				showMessage("Invite");
//				Log.v("ContactList", "Invite");
////				super.onChange(arg0);
//			}
//		});
		cursorInvited.registerContentObserver(new MyObserver(new Handler()));
	}

	private void bindService(){
		bindService((new Intent()).setComponent(
                com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
                mConnection, 0);
	}
	
	private String convertPresenseStatusToText(String textId){
		switch(Integer.parseInt(textId)){
		case Im.Presence.AVAILABLE:
			return "available";
		case Im.Presence.AWAY:
			return "away";
		case Im.Presence.DO_NOT_DISTURB:
			return "do not disturb";
		case Im.Presence.IDLE:
			return "idle";
		case Im.Presence.INVISIBLE:
			return "invisible";
		case Im.Presence.OFFLINE:
			return "offline";
			default:
				return "No status";
		}
	}
	
	private void showMessage(String message){
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the GTalkService has been
            // established, giving us the service object we can use to
            // interact with the service. We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            IGTalkService GTalkService = IGTalkService.Stub.asInterface(service);

            try {
                mGTalkSession = GTalkService.getDefaultSession();
                
                if (mGTalkSession == null) {
                    // this should not happen.
                    showMessage("Session not found");
                    return;
                }
            } catch (DeadObjectException ex) {
                showMessage("Session not found");
            }
//
//            mSendButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mGTalkSession = null;
            showMessage("Service Disconnect!!");
        }
    };

    private class MyObserver extends ContentObserver{

		public MyObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean arg0) {
			String request = new String("-");
			cursorInvited = contentResolver.query(Im.Subscriptions.CONTENT_URI, null, null, null, null);
			int columnIndex = cursorInvited.getColumnIndex(Im.Subscriptions.USERNAME);
			int count = cursorInvited.count();
			if(count > 0)
				cursorInvited.next();
			if(cursorInvited.first()){
				do{
					request = request+", "+cursorInvited.getString(columnIndex);
				}while(cursorInvited.next());
			}
			showMessage(request);
		}
    	
    }
}
